<script setup lang="ts">
import type { VbenFormSchema } from '@vben/common-ui';

import { computed, onMounted, reactive, ref } from 'vue';

import { AuthenticationLogin, z } from '@vben/common-ui';
import { useI18n } from '@vben/locales';
import { Input } from 'ant-design-vue';

import { getCaptcha, LoginIn } from '#/api/captcha';
import { useAccessStore } from '@vben/stores';
import { useRouter } from 'vue-router';
import { preferences } from '@vben/preferences';
import { notification } from 'ant-design-vue';

const { t } = useI18n();

const captchaImg = ref('');
const captchaKey = ref('');
const accessStore = useAccessStore();
const router = useRouter();

async function refreshCaptcha() {
  const { captchaImage, captchaKey: key } = await getCaptcha();
  console.log(captchaImage, key);
  captchaImg.value = captchaImage;
  captchaKey.value = key;
}

onMounted(refreshCaptcha);
const schemas = computed((): VbenFormSchema[] => [
  {
    component: 'VbenInput',
    componentProps: {
      placeholder: t('authentication.usernameTip'),
    },
    fieldName: 'username',
    label: t('authentication.username'),
    rules: z.string().min(1, { message: t('authentication.usernameTip') }),
  },
  {
    component: 'VbenInputPassword',
    componentProps: {
      placeholder: t('authentication.password'),
    },
    fieldName: 'password',
    label: t('authentication.password'),
    rules: z.string().min(1, { message: t('authentication.passwordTip') }),
  },
]);

const captchaValue = ref('');

async function onSubmit(values: Record<string, any>) {
  try {
    const result = await LoginIn({
      username: values.username,
      password: values.password,
      captchaCode: captchaValue.value,
      captchaKey: captchaKey.value,
    });
    const token = result?.token;
    if (token) {
      localStorage.setItem('token', token);
      notification.success({
        message: '登录成功',
        description: `欢迎 ${result?.username ?? ''}`,
        duration: 2,
      });
      try {
        await router.push('/staff/users');
      } catch (navError) {
        console.error('跳转失败:', navError);
        // 兜底：强制刷新到首页
        window.location.href = '/staff/users';
      }
    } else {
      notification.error({
        message: '登录失败',
        description: result?.message || '登录失败，请检查用户名和密码',
        duration: 3,
      });
      // 刷新验证码
      await refreshCaptcha();
    }
  } catch (error: any) {
    console.error('登录异常:', error);
    notification.error({
      message: '登录异常',
      description: error?.response?.data?.message || error?.message || '服务器异常，请稍后重试',
      duration: 4,
    });
    // 刷新验证码
    await refreshCaptcha();
  }
}
</script>

<template>
  <div>
    <AuthenticationLogin
      :form-schema="schemas"
      :show-forget-password="false"
      :show-register="false"
      :show-remember-me="false"
      :show-third-party-login="false"
      @submit="onSubmit"
    >
      <template #captcha>
        <div class="flex items-center gap-2 mb-4">
          <Input
            v-model:value="captchaValue"
            placeholder="请输入验证码"
            class="flex-[3] h-10"
          />
          <img
            v-if="captchaImg"
            :src="captchaImg"
            alt="验证码"
            title="点击刷新验证码"
            class="h-10 flex-1 rounded-md border border-gray-200 object-cover cursor-pointer select-none transition hover:opacity-90"
            @click="refreshCaptcha"
          />
          <button
            v-else
            type="button"
            class="h-10 flex-1 rounded-md border border-dashed text-gray-500 hover:text-gray-700 cursor-pointer text-sm"
            @click="refreshCaptcha"
          >
            获取验证码
          </button>
        </div>
      </template>
    </AuthenticationLogin>
  </div>
</template>
